package com.xinbochuang.machine.admin.controller.common;

import com.xinbochuang.machine.admin.config.MinioData;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.common.utils.FastDFSClient;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

/**
 * @author whz
 * @date 2018/7/16
 */
@Slf4j
@Api(tags = {"文件管理"})
@RestController
@RequestMapping("/api/file/")
public class FileController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private FastDFSClient fastdfsClientUtil;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioData minioData;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        String path = "";
//        try {
//            path = fastdfsClientUtil.uploadFile(file);
////            path= UUID.randomUUID().toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        } else {
            try {
                final InputStream is = file.getInputStream();
                // 文件名
                path = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                // 把文件放到minio的boots桶里面
                minioClient.putObject(minioData.getBucketNameImage(), path, is, new PutObjectOptions(is.available(), -1));
                // 关闭输入流
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 得到文件流
            return AjaxResult.data(path);
        }
    }

    @GetMapping("/downloadFile")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        InputStream in = null;
        try {
            final ObjectStat stat = minioClient.statObject(minioData.getBucketNameImage(), fileName);
            response.setContentType(stat.contentType());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            in = minioClient.getObject(minioData.getBucketNameImage(), fileName);
            IOUtils.copy(in, response.getOutputStream());
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
//        /**
//         * 下载文件
//         *
//         * @param filePath
//         * @param response
//         * @return
//         */
//    @RequestMapping("/downloadFile")
//    public AjaxResult downloadFile(@RequestParam("filePath") String filePath, HttpServletResponse response) {
//        int index = filePath.lastIndexOf("/");
//        String fileName = filePath.substring(index + 1);
//        try {
//            byte[] bytes = fastdfsClientUtil.downloadFile(filePath);
//            InputStream inputStream = new ByteArrayInputStream(bytes);
//            response.setHeader("content-type", "application/octet-stream");
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//
//            byte[] buff = new byte[1024];
//            BufferedInputStream bis = new BufferedInputStream(inputStream);
//            OutputStream os = response.getOutputStream();
//            int i = bis.read(buff);
//            while (i != -1) {
//                os.write(buff, 0, buff.length);
//                os.flush();
//                i = bis.read(buff);
//            }
//            os.close();
//            bis.close();
//            logger.info("Download  successfully!");
//
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return AjaxResult.ok();
//
//    }
//
//    /**
//     * 删除文件
//     *
//     * @param filePath
//     * @return
//     */
//    @RequestMapping("/deleteFile")
//    @ResponseBody
//    public AjaxResult deleteFile(@RequestParam("filePath") String filePath) {
//        fastdfsClientUtil.deleteFile(filePath);
//        return AjaxResult.error("删除文件成功");
//    }
//
//    /**
//     * 上传图片，并且生成缩略图
//     */
//
//    @RequestMapping("/uploadImageAndCrtThumbImage")
//    public AjaxResult uploadImageAndCrtThumbImage(@RequestParam("file") MultipartFile file, Model view) {
//        Map<String, String> map = null;
//        try {
//            //上传图片，并且生成缩略图的方法
//            map = fastdfsClientUtil.uploadImageAndCrtThumbImage(file);
//
//            view.addAttribute("uri", map.get("path"));//原图片地址
//            view.addAttribute("slavePath", map.get("slavePath"));  //缩略图地址
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return AjaxResult.data(map);
//    }

}
